﻿using System;
using System.Linq;

namespace yMethod
{
    /// <summary>
    /// 转换器
    /// </summary>
    public class Convert
    {
        /// <summary>
        /// bool数组转换为byte数组，byte数组的长度由bool数组的长度决定
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static byte[] BoolsToBytes(bool[] value)
        {
            int byteLength = value.Length % 8 == 0 ? value.Length / 8 : value.Length / 8 + 1;

            byte[] result = new byte[byteLength];

            for (int i = 0; i < result.Length; i++)
            {

                int total = value.Length < 8 * (i + 1) ? value.Length - 8 * i : 8;

                for (int j = 0; j < total; j++)
                {
                    result[i] = SetBitValue(result[i], j, value[8 * i + j]);
                }
            }
            return result;
        }

        public static byte SetBitValue(byte src, int bit, bool value)
        {
            return value ? (byte)(src | (byte)Math.Pow(2, bit)) : (byte)(src & ~(byte)Math.Pow(2, bit));
        }

        /// <summary>
        /// byte转换为特定长度的bool数组
        /// </summary>
        /// <param name="value"></param>
        /// <param name="length"></param>
        /// <param name="isReverse"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public static bool[] ByteToBoolArray(byte value, int length, bool isReverse = false)
        {
            if (length < 0 || length > 8)
                throw new ArgumentOutOfRangeException(nameof(length), "Length must be between 0 and 8.");

            bool[] result = new bool[length];
            for (int i = 0; i < length; i++)
            {
                result[i] = (value & (1 << i)) != 0;
            }
            return isReverse ? result.Reverse().ToArray() : result;
        }
    }
}
